<template>
	<view class="left clearfix bai" style="background:#fff;border-radius: 5px;">
		<view class="left clearfix bai">
		<view class="breadcrumb-box left clearfix">
			 <uni-breadcrumb separator="/">
			    <uni-breadcrumb-item v-for="(route,index) in routes" :key="index" :to="route.to">
			           {{route.name}}
				</uni-breadcrumb-item>
			</uni-breadcrumb>
		</view>
		
		<!--内容列表-->
		<view class="content-box left clearfix">
			<textarea @input="setFontLength" @blur="setFontLength" :maxlength="1600" placeholder="请输入配音文案" v-model="content"></textarea>
		</view>
		
		<!--内容生成按钮-->
		<view class="content-sheng-box left clearfix">
			<view class="content-botton left" @click="getMessage('deepseek-r1')">DeepSeek</view>
			<view class="content-botton left"  @click="getMessage('qwen-plus')">通义千问</view>
			<view class="content-ren left" style="line-height:30px;font-size:14px;color:#666;margin-left:50px;">
				{{fontNumber}}字
			</view>
			<view class="content-ren right" @click="selectTimbre()" style="cursor:pointer;">
				<view class="content-image left">
					<image :src="currentTimbre.avatar" mode="aspectFill" style="width:100%;height:100%;"></image>
				</view>
				<view class="content-user left">
					{{currentTimbre.name}}
				</view>
			</view>
		</view>
		
		<!--语调和语速-->
		<view class="content-yudiao left clearfix">
			
		</view>
		
		<view class="content-submit-box left" @click="submitDud()">
			开始配音
		</view>
		</view>
		
		<uni-popup type="center" ref="timbrePopup">
			<view class="b-box left clearfix relative">
				<view class="b-close absolute" @click="this.$refs.timbrePopup.close()">
					<uni-icons type="closeempty" size="20" color="#999"></uni-icons>
				</view>
				<view class="b-content left clearfix bai">
					<view class="b-item left clearfix bai" v-for="(item,index) in timbreData">
						<view class="b-header-image left">
							<image :src="item.avatar" mode="aspectFill"></image>
						</view>
						<view class="b-name left bai" style="margin-top:5px;">
							{{item.name}}
						</view>
						
						<view class="b-name left bai" style="margin-top:5px;cursor:pointer;">
							<uni-icons v-if="currentPlayAudioIndex!=index || currentPlayAudioStatus=='pause' || currentPlayAudioIndex===null" type="icon-bofang2" size="15" @click="setPlay(item,'play',index)" color="#00c296" custom-prefix="iconfont"></uni-icons>
							<uni-icons v-if="currentPlayAudioIndex==index && currentPlayAudioStatus=='play'" type="icon-weibiaoti519" size="15" @click="setPlay(item,'pause',index)" color="#00c296" custom-prefix="iconfont"></uni-icons>
						</view>
						
						<view class="b-name left bai" @click="setSelectTimbre(item,index)">
							<view>使用</view>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>


<style scoped>
	.b-name view{width:70%;height:25px;line-height:25px;text-align: center;background:#00c296;color:#fff;border-radius: 5px;margin-left:15%;margin-top:5px;cursor:pointer;}
	.b-name{line-height:20px;text-align: center;font-size:12px;color:#333;}
	.b-header-image image{width:100%;height:100%;}
	.b-header-image{width:50px;height:50px;border-radius: 50%;overflow: hidden;margin-left:20px;margin-top:10px;}
	.b-content{width:820px;height:400px;overflow: auto;}
	.b-item{width:90px;height:150px;border-radius: 5px;margin-left:20px;margin-top:20px;box-shadow: 1px 2px 8px 0 rgb(0 0 0 / 10%);}
	.b-close{right:10px;top:10px;cursor:pointer;}
	.b-box{width:820px;height:400px;background:#fff;border-radius: 5px;}
	.content-submit-box{width:50%;margin-left:25%;line-height:40px;text-align: center;font-size:14px;background:#2979ff;color:#fff;margin-top:50px;margin-bottom:50px;border-radius: 5px;cursor:pointer;}
	.content-user{line-height:40px;font-size:14px;margin-left:5px;color:#333;}
	.content-image{width:35px;height:35px;border-radius: 50%;margin:2.5px;overflow: hidden;}
	.content-ren{height:40px;min-width:100px;}
	.content-botton{padding-left:20px;padding-right:20px;line-height:30px;background:#eee;border-radius: 5px;float:left;margin-left: 10px;margin-right:10px;font-size:14px;color:#666;cursor:pointer;}
	.content-sheng-box{width:90%;margin-left:5%;height:40px;margin-top:20px;}
	.content-box textarea{width:96%;margin-left:2%;margin-top:10px;line-height:1.5rem;font-size:14px;color:#333;min-height:490px;}
	.content-box{width:90%;height:500px;margin-top:50px;margin-left:5%;border:1px solid #ccc;border-radius: 5px;}
	.breadcrumb-box{width:80%;height:40px;line-height:40px;margin-left:30px;}
</style>



<script>
	var db = uniCloud.database();
	import common from '@/utils/common.js'; 
	var application = uniCloud.importObject('application',{customUI:true});
	var aliyun = uniCloud.importObject('aliyun',{customUI:true});
	export default {
		data() {
			return {
				timbreData:[],//音色列表
				routes: [
				        {
				          to: "/A",
				          name: "配音管理",
				        },
				        {
				          to: "/B",
				          name: "配音",
				        }
				      ],
					  
			 content:'',//内容
			 innerAudioContext:null,//音频播放数据
			 audioItem:{},//正在播放的数据
			 currentPlayAudioIndex:null,//当前正在播放的index
			 currentPlayAudioStatus:null,//当前播放状态
			 currentTimbre:{},//当前使用的音色
			 fontNumber:0,
			 taskId:'',//task_id
			 ws:{},
			 text:'',
			 id:'',
			 parentId:''
			}
		},
		onLoad(e) {
			if(!e || !e.id || !e.parentId){
				uni.showToast({
					title:'缺少id参数',
					icon:'error',
					duration:2000
				})
				return false;
			}else{
				this.id = e.id;
				this.parentId = e.parentId;
				//查询出默认内容
				this.getDefaultData(this.id);
			}
			
		},
		created() {
			var that = this;
			//查询出对应的音色
			this.getTimbreData();
			//先查询出来是否有缓存的音色
			setTimeout(function(){
				uni.getStorage({
					key:'current-timbre',
					success:function(e){
						that.currentTimbre = e.data;
					},
					fail() {
						that.currentTimbre = that.timbreData[0];
					}
				})
			},1000);
			
		},
		methods: {
			//内容发生变化时统计字数
			setFontLength(){
				this.fontNumber = this.content.length;
			},
			//查询出默认内容
			getDefaultData(id){
				db.collection('timbre_title').where({_id:id}).get({getOne:true}).then(res=>{
					this.content = res.result.data.content;
				});
			},
			//点击开始配音以后
			submitDud(){
				var that = this;
				var content = this.content;
				var timbre = this.currentTimbre;
				var length = content.length;
				var id = this.id;
				console.log('字数',length);
				if(!id){
					uni.showToast({
						title:'缺少id参数，配音无法执行',
						icon:'error',
						duration:2000
					})
					
					return false;
				}
				
				if(!content){
					uni.showToast({
						title:'请输入文本内容',
						icon:'error',
						duration:2000
					})
					
					return false;
				}
				
				if(length > 1600){
					uni.showToast({
						title:'当前字数为'+length+',超出了1600字',
						icon:'none',
						duration:2000
					})
					
					return false;
				}
				uni.showLoading({
					title:'合成中，大约需要2分钟'
				})
				var fileName = common.uuid();
				console.log('文件名',fileName);
				var data = {
					text:content,//合成文本
					voice:timbre.voice,//音色
					volume:100,//音量
					rate:1,//语速
					pitch:1,//语调,
					fileName:fileName
				}
				// 创建一个新的Date对象
				const today = new Date();
				// 获取年、月、日
				const year = today.getFullYear();
				const month = (today.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始的，所以需要+1
				const day = today.getDate().toString().padStart(2, '0');
				// 使用模板字符串组合日期
				const formattedDate = `${year}${month}${day}`;
				var filePath = 'http://mofang.yipaidaojia.com/public/'+formattedDate+'/'+fileName+'.mp3';
				//更新到数据库
				db.collection('timbre_title').where({_id:this.id}).update({
					audio:filePath,
					content:content
				}).then(addRes=>{
					//异步发送给接口
					aliyun.getCosyVoiceFromPhp(data);
					uni.showToast({
						title:'配音成功',
						icon:'error',
						duration:2000
					})
					setTimeout(function(){
						uni.redirectTo({
							url: '/pages/timbre_title/chapter?id='+that.parentId
						});
					},2000);
				}).catch(err=>{
					console.log('出错了',err);
				});
				
				
			},
			
			//根据固定长度将字符串转化为数组
			splitStringByLength(str, length) {
			    let result = [];
			    for (let i = 0; i < str.length; i += length) {
			        result.push(str.slice(i, i + length));
			    }
			    return result;
			},
			
			//点击使用音色以后
			setSelectTimbre(item,index){
				var that = this;
				//把当前使用的音色缓存起来，以便以后继续使用
				uni.setStorage({
					key:'current-timbre',
					data:item,
					success() {
						that.currentTimbre = item;
						that.$refs.timbrePopup.close();
					}
				})
			},
			//设置播放音频
			setPlay(item,act,index){
				var that = this;
				if(item.audio_url != this.audioItem.audio_url){
					if(that.innerAudioContext){
						that.innerAudioContext.stop();
					}
					var innerAudioContext = uni.createInnerAudioContext();
					this.innerAudioContext = innerAudioContext;
					this.audioItem = item;
					innerAudioContext.src = item.audio_url;
					innerAudioContext.autoplay = true;
				}else{
					var innerAudioContext = this.innerAudioContext;
				}
				
				if(act == 'play'){
					innerAudioContext.play();
					innerAudioContext.onPlay(()=>{
						that.currentPlayAudioIndex = index;
						that.currentPlayAudioStatus = 'play';
					});
				}else if(act == 'pause'){
					innerAudioContext.pause();
					that.currentPlayAudioStatus = 'pause';
				}
				
				innerAudioContext.onEnded(()=>{
					that.currentPlayAudioStatus = 'pause';
				});
			},
			//弹出选择音色
			selectTimbre(){
				this.$refs.timbrePopup.open();
			},
			//查询出对应的音色
			getTimbreData(){
				db.collection('timbre').where({type:'cosyvoice'}).orderBy('_id desc').get().then(res=>{
					this.timbreData = res.result.data;
				});
			},
			//利用Ai获取文本
			getMessage(model){
				var that = this;
				var content = this.content;
				if(!content){
					uni.showToast({
						title:'请输入生成关键词',
						icon:'none',
						duration:2000
					})
					
					return false;
				}
				uni.showLoading({
					title:'创作中'
				})
				var newContent = content+' 将以上内容改编成幽默生动且丰富的内容，1500字';
				var  data = {
					url:'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
					headers:{
						"Cache-Control": "no-cache",
						"Content-type": "application/json",
						'Authorization': 'Bearer sk-4a0cd1cdc85147c785ea8a8ddd1dcd38'
					},
					body:{
						  model: model,
						  messages: [
								  {
									  "role": "user", 
									  "content": newContent
								  }
							  ],
							  stream:false
						},
					method:'POST'
				}
				
				uni.request({
				    url: data.url,
				    data: data.body,
				    header: data.headers,
					timeout:200000,
					method:data.method,
				    success: (res) => {
						uni.hideLoading()
				        that.content = res.data.choices[0].message.content;
						that.fontNumber = that.content.length;
				    },
					fail(err) {
						uni.hideLoading()
						console.log('请求失败',err)
					}
				});
				
				
			}
		}
	}
</script>
